package com.jingzhi.count.config.shiro;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.jingzhi.count.entity.Team;
import com.jingzhi.count.mapper.TeamMapper;
import com.jingzhi.count.mapper.UserTokenMapper;
import com.jingzhi.count.service.TeamService;
import com.jingzhi.count.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class StatelessAuthcFilter extends AccessControlFilter {

    private TeamMapper teamMapper;

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        return false;
    }

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //1、客户端传递的token
        String token = request.getParameter("token");
        String callbackFunction = request.getParameter("callbackparams");
        try {
            if (StringUtils.isBlank(token)) {
                onLoginFail(response, callbackFunction);
                return false;
            }
            JWTUtil.verify(token);
            String acount = JWTUtil.getUsername(token);
            Team team = teamMapper.selectByAccount(acount);
            if(team==null){
                onLoginFail(response, callbackFunction);
                return false;
            }
            request.setAttribute("team",team);

        } catch (Exception e) {
            onLoginFail(response, callbackFunction);
            return false;
        }
        return true;
    }

    //认证失败时处理方法
    private void onLoginFail(ServletResponse response, String callbackFunction) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("utf8");
        JSONObject json = new JSONObject(true);
        json.put("rc", "0");
        json.put("des", "token无效！");
        if (StringUtils.isBlank(callbackFunction)) {//不是ajax的jsonp请求
            httpResponse.setContentType("application/json");
            httpResponse.getWriter().write(json.toJSONString());
            System.out.println(json.toJSONString());
            return;
        }
        httpResponse.setContentType("text/javascript");
        System.out.println(callbackFunction + "(" + json.toJSONString() + ")");
        httpResponse.getWriter().write(callbackFunction + "(" + json.toJSONString() + ")");

    }

    /*
     * 预处理阶段 初始化userTokenMapper
     */
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        ServletContext context = request.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        teamMapper = ctx.getBean(TeamMapper.class);
        return super.onPreHandle(request, response, mappedValue);
    }


}